package com.pj.wisdomlogistics.ui.activity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.pj.wisdomlogistics.BuildConfig;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.User;
import com.pj.wisdomlogistics.entity.VersionEntity;
import com.pj.wisdomlogistics.mvp.contract.SplashContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.SplashPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.view.CustomAlertDialog;
import com.pj.wisdomlogistics.ui.view.NumberProgressDialog;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.SPUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import rx.Observable;
import rx.functions.Func1;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;

public class SplashActivity extends MvpActivity<SplashPresenter> implements SplashContract.View, BaseActivity.RequestPermission {
    private static final String TAG = "SplashActivity";
    private long mSplashStartMillis;
    private String downloadUrl = "";
    private NumberProgressDialog mNumberProgressDialog;

    private CustomAlertDialog mCustomAlertDialog;

    private String userName;
    private String password;


    @Override
    public void initView() {
        ultimateBar.setImmersionBar();

        mSplashStartMillis = System.currentTimeMillis();
        setRequestPermissionListener(this);
        MyApplication.loadUser();

        Intent mIntent = getIntent();
        userName = mIntent.getStringExtra("userName");
        if(!TextUtils.isEmpty(userName)){
            MyApplication.isJc = true;
        }
        password = getUidFromBase64(mIntent.getStringExtra("password"));
    }

    @Override
    public void initData() {
        mPresenter.checkVersion();
    }

    public void init() {
        File apk = new File(getDownloadDir(), "WLogistics.apk");
        if (apk.exists()) {
            apk.delete();
        }

        if (!TextUtils.isEmpty(MyApplication.token) && TextUtils.isEmpty(userName)) {
            Log.e("Tag" , "1");
            mPresenter.checkLogin(MyApplication.token);
        } else if (!TextUtils.isEmpty(userName)) {
            Log.e("Tag" , "2");
            mPresenter.login_jc(userName);
        } else {
            Log.e("Tag" , "3");
            SPUtils.saveUser(null);
            MyApplication.loadUser();
            splash(LoginActivity.class);
        }
    }

    @Override
    public int getContentView() {
        return R.layout.activity_splash;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void showCheckResult(User user) {
        SPUtils.saveUser(user);
        MyApplication.loadUser();
        splash(MainActivity.class);
    }

    @Override
    public void showVersion(final VersionEntity version) {
        if (version != null) {
            String remoteVersion = version.getVersion();

            if (BuildConfig.VERSION_NAME.compareTo(remoteVersion) == -1 && !MyApplication.isJc) {
                mCustomAlertDialog = new CustomAlertDialog.Builder(this)
                        .setMessage("发现新版本，请及时更新")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                downloadUrl = version.getLinkUrl();

                                if (checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    getNewVersion(downloadUrl);
                                } else {
                                    requestSystemPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 666);
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                init();
                            }
                        }).create();
                mCustomAlertDialog.show();
            } else {
                init();
            }
        }
    }

    @Override
    public void onError(int errorCode, String errorMsg , String error) {
        if (errorCode == 0 || errorCode == Cons.ResponseCons.EX_CODE_OVERTIME) {

            SPUtils.saveUser(null);
            MyApplication.loadUser();
            startActivity(LoginActivity.class);
            ActivityManagerUtil.create().finishActivity();
        }
        if (MyApplication.isJc) {

            Intent intent = new Intent();
            intent.setAction("com.wf.boom.test");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else {
            startActivity(LoginActivity.class);
            ActivityManagerUtil.create().finishActivity();
        }
    }

    @Override
    public void showLoginSuccess(User user) {
        SPUtils.saveUser(user);
        MyApplication.loadUser();
        Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
        startActivity(MainActivity.class);
        ActivityManagerUtil.create().finishActivity();
    }

    public void splash(final Class clazz) {
        long splashTime = 3000 - (System.currentTimeMillis() - mSplashStartMillis);
        splashTime = splashTime > 0 ? splashTime : 0;
        Observable.timer(splashTime, TimeUnit.MILLISECONDS).map(new Func1<Long, Object>() {
            @Override
            public Object call(Long mLong) {
                startActivity(clazz);
                ActivityManagerUtil.create().finishActivity(SplashActivity.this);
                return null;
            }
        }).subscribe();

    }

    @Override
    public void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 666) {
            if (checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                getNewVersion(downloadUrl);
            }
        } else {
            Toast.makeText(this, "权限被拒绝，无法操作", Toast.LENGTH_SHORT).show();
            init();
        }
    }

    public static final String getDownloadDir() {
        File pbcDownload = new File(Environment.getExternalStorageDirectory(), "WLogisticsDownload");
        if (!pbcDownload.exists()) {
            pbcDownload.mkdir();
        }
        return pbcDownload.getAbsolutePath();
    }

    private void getNewVersion(String url) {
        if (!MyApplication.isNetOk) {
            Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
            return;
        }

        if (mCustomAlertDialog.isShowing()) {
            mCustomAlertDialog.dismiss();
        }

        mNumberProgressDialog = new NumberProgressDialog(this);
        mNumberProgressDialog.show();
        Disposable disposable = RxDownload.getInstance(this)
                .download(url, "WLogistics.apk", getDownloadDir())                       //只传url即可
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DownloadStatus>() {
                    @Override
                    public void accept(DownloadStatus status) throws Exception {
                        //DownloadStatus为下载进度
                        Log.e(TAG, "accept: " + status.getPercent());
                        mNumberProgressDialog.setProgress((int) status.getPercentNumber());

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        //下载失败
                        Log.e(TAG, "下载失败: ");
                        mNumberProgressDialog.dismiss();
                        init();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //下载成功
                        Log.e(TAG, "下载成功: ");
                        mNumberProgressDialog.dismiss();
                        File apk = new File(getDownloadDir(), "WLogistics.apk");
                        if (Build.VERSION.SDK_INT < 23) {
                            Log.e(TAG, "1 ");
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
                            Log.e(TAG, "2 ");
                            startActivity(intent);
                            Log.e(TAG, "3 ");
                            ActivityManagerUtil.create().finishActivity();
                            Log.e(TAG, "4 ");
                        } else {
                            if (apk.exists()) {
                                openFile(apk, SplashActivity.this);
                            }
                        }

                    }
                });
    }

    @SuppressLint("WrongConstant")
    public void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }

    }

    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

    public static String getUidFromBase64(String base64Id) {
        String result = "";
        if (!TextUtils.isEmpty(base64Id)) {
            if (!TextUtils.isEmpty(base64Id)) {
                result = new String(Base64.decode(base64Id.getBytes(), Base64.DEFAULT));
            }
        }
        return result;
    }
}
